package com.bbc.third.taobao;

import org.springframework.stereotype.Service;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.request.ShopGetRequest;
import com.taobao.api.response.ItemGetResponse;
import com.taobao.api.response.ItemcatsGetResponse;
import com.taobao.api.response.ShopGetResponse;

@Service
public class TBApi {
	
	public static final String key = "tb";
	private static final String serverUrl = "http://gw.api.taobao.com/router/rest";
	private static final String appKey = "21253684";
	private static final String appSecret = "f680b5d32a6acd2e52bebbda8b974930";
	
	private TaobaoClient tbclient;
	
	public TaobaoClient getClient() {
		if (tbclient == null) {
			tbclient=new DefaultTaobaoClient(serverUrl,appKey,appSecret);
		}
		return tbclient;
	}
	
	public ItemcatsGetResponse getType(String parentCid) {
		ItemcatsGetRequest req=new ItemcatsGetRequest();
		req.setFields("cid,parent_cid,name,is_parent");
		try {
			req.setParentCid(Long.valueOf(parentCid)); 
			ItemcatsGetResponse response = getClient().execute(req);
			return response;
		} catch (ApiException e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	public ItemGetResponse getProduct(Long productId) {
		ItemGetRequest req=new ItemGetRequest();
		req.setFields("detail_url,num_iid,title,nick,type,props_name,cid,pic_url,price");
		req.setNumIid(productId);
		try {
			ItemGetResponse response = getClient().execute(req);
			return response;
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public ShopGetResponse getShop(String nick) {
		ShopGetRequest req=new ShopGetRequest();
		req.setFields("sid,cid,nick,title,pic_path,shop_score");
		req.setNick(nick);
		try {
			ShopGetResponse response = getClient().execute(req);
			return response;
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}

}
